/**
 * 角色的新增，编辑模式的控制
 * 角色的增删改查接口的调用
 */
import {Component, OnInit, EventEmitter, Input, OnDestroy} from '@angular/core';
import {Output} from "@angular/core/src/metadata/directives";
import {PaginationModel} from "../../../common-module/pagenation-component/pagination.model";
import {RoleService} from "../service/role-service/role.service";
import * as $ from 'jquery';
import * as _ from 'lodash';
import {EventService} from "../service/event-service/event.service";

@Component({
  selector: 'iotek-role-list',
  templateUrl: './role-list.component.html',
  styleUrls: ['./role-list.component.less'],
  providers: [RoleService]
})
export class RoleListComponent implements OnInit , OnDestroy{

  pageTotal = 0;
  pageSize = 10;
  editable = false; // true:可编辑行
  isNew = false; //true:增加添加行
  newRole = ""; //新添加角色
  roles: any;  //角色列表
  isClosed = false; // 标志窗口是否关闭
  public toastConfig = {};
  private drapRoleConfig = {};
  private currentPageNo = 1;
  private subList = [];

  constructor(private roleService: RoleService, private eventService: EventService) {
    var sub1 = this.eventService.dragStartEvent.subscribe(value => {
      this.drapRoleConfig = value;
    });
    var sub2 = this.eventService.dropEvent.subscribe(value => {
      if((value['to'] == this.type && (value['to']) != this.drapRoleConfig['from'])) {
        var toSaveRole = {
          'newName':this.drapRoleConfig['value']['name'],
          'type': +this.type,
          'id': this.drapRoleConfig['value']['id']
        };
        this.save(toSaveRole).then(() => {
          this.eventService.emitUpdateEvent({});
        });
      }

    });

    var sub3 = this.eventService.updateEvent.subscribe(() => {
      this.getRoles(this.currentPageNo)
    });
    this.subList.push(sub1);
    this.subList.push(sub2);
    this.subList.push(sub3);
  }

  ngOnInit() {
    this.getRoles(this.currentPageNo);
  }

  ngOnDestroy(): void {
    this.subList[0].unsubscribe();
    this.subList[1].unsubscribe();
    this.subList[2].unsubscribe();
  }
//自定义onclose事件，通知父组件关闭窗口
  @Output('onclose') closed = new EventEmitter<any>();

//自定义输入属性 title、type
  @Input() title: string;
  @Input() type: string;

//引入pagination component
  public pager: PaginationModel = new PaginationModel(this.pageTotal, 1, this.pageNoClickCallback, 'md');

// pagination 点击事件
  private pageNoClickCallback: (number) => void = (pn: number) => {
    this.currentPageNo = pn;
    this.getRoles(pn);
  }

//click事件关闭窗口
  closeWindow() {
    this.isClosed = !this.isClosed;
    this.closed.emit({closed: this.isClosed, type: this.type});
  }
//获取角色列表
  getRoles(pn) {
    this.roleService.getRoles(this.type, pn, this.pageSize).then((res)=> {
      this.roles = res.resultList;
      this.pageTotal = res.totalPage;
      this.pager = new PaginationModel(this.pageTotal, pn, this.pageNoClickCallback, 'md');
    });
  }

// 切换成编辑模式，并自动获取焦点
  edit(roleId) {
    this.editable = true;
    setTimeout(() => {
      $(`#roleId-${roleId}`).focus();
    });

  }

// 切换成添加模式
  addRole() {
    this.isNew = true;
    setTimeout(() => {
      $(`#newRole`).focus();
    });
  }

//取消编辑模式并保存
  editNewRole(role) {
    if (role) {
      this.save(
        {id: role.id,
          newName: role.name,
          type: role.type
        });
    }
  }
  //封装新增信息，并保存
  saveNewRole(name){
    this.save({'newName':name,'type':this.type});
  }
//esc 取消编辑，添加模式，并重新加载数据
  cancel() {
    this.isNew = false;
    this.editable = false;
    this.getRoles(this.currentPageNo);
  }
  // 保存修改
  save(role) {
    return this.roleService.save(role).then((res)=> {
      this.editable = false;
      this.isNew = false;
      this.toastConfig = {
        title: res.title,
        type: res.status.toLowerCase(),
        content:  res.title,
        random: Math.random()
      };
      this.getRoles(this.currentPageNo);
    })
  }

//删除角色
  delete(id) {
    this.roleService.delete(id).then((res)=> {
      this.toastConfig = {
        title: res.title,
        type: res.status.toLowerCase(),
        content: res.content,
        random: Math.random()
      };
      this.getRoles(this.currentPageNo);
    })
  }
  public onDragStart($event, role) {
    this.eventService.emitDragStartEvent({
      from: this.type,
      value: role
    });
  }

  public onTableDragOver($event) {
    $event.preventDefault();

  }
  public onDragDrop($event) {
    this.eventService.emitDropEvent({
      to: this.type
    });
  }

  private updateRoleList() {
    this.getRoles(this.currentPageNo);
  }

}
